package se_user

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"time"
	cache2 "wx-api/dsp-api/cache"
	config2 "wx-api/dsp-api/config"
	"wx-api/dsp-api/errmsg"
	"wx-api/dsp-api/handlers"
	"wx-api/dsp-api/model/user"
	"wx-api/dsp-api/utils"
)

type UserLogin struct {
	UserName string `form:"username" json:"username" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

func Login(c *handlers.Controller) {
	var form UserLogin
	if err := c.Ctx.ShouldBind(&form); err != nil {
		fmt.Println(err)
		c.BadRequest()
		return
	}
	if form.UserName == "" || form.Password == "" {
		c.SetErrorMsg(nil, errmsg.GetError("email or password is empty"))
		return
	}
	info, ok := user.SeachEmail(form.UserName)
	if !ok {
		c.SetErrorMsg(nil, errmsg.GetError("登陆失败，请联系管理员"))
		return
	}

	if info.Flag == 2 || info.Status == 2 {
		c.SetErrorMsg(nil, errmsg.GetError("登陆失败，账户被冻结"))
		return
	}

	if utils.MD5(form.Password) != info.Password {
		c.SetErrorMsg(nil, errmsg.GetError("登陆失败，密码错误"))
		return
	}
	tmptoken := utils.MD5(info.Password + time.Now().Format("2006-01-02 15:04:05") + info.Id.Hex())
	conn := config2.RedisDb.Get()
	defer conn.Close()
	_, _ = redis.String(conn.Do("SET", "dsp_login-"+tmptoken, info.Id.Hex()))
	//设置过期时间
	_, _ = conn.Do("EXPIRE", "dsp_login-"+tmptoken, 6*60*60)

	ret := make(map[string]interface{})
	ret["token"] = tmptoken
	ret["name"] = info.Name

	c.SetErrorMsg(ret, errmsg.SuccessMsg())
	return
}
func LoginOut(c *handlers.Controller) {
	tmptoken := c.Ctx.GetHeader("token")
	conn := config2.RedisDb.Get()
	defer conn.Close()
	token, err := redis.String(conn.Do("GET", "dsp_login-"+tmptoken))
	if token != "" && token == tmptoken {
		conn.Do("DEL", "dsp_login-"+tmptoken)
	}
	if err != nil {
		fmt.Println("redis loginout error:", err.Error())
	}
	c.SetErrorMsg(nil, errmsg.SuccessMsg())
	return
}
func GetUserInfo(c *handlers.Controller) {
	uid, ok := c.Ctx.Get("dspuser")
	if !ok {
		c.SetErrorMsg(nil, errmsg.GetError("uid is empty"))
		return
	}
	info, ok := cache2.CacheDspUserMapNGet(uid.(string))
	if !ok {
		c.SetErrorMsg(nil, errmsg.GetError("uid cache is empty"))
		return
	}
	ret := make(map[string]interface{})
	ret["name"] = info.Name
	ret["email"] = info.Email
	ret["phone"] = info.Phone

	c.SetErrorMsg(ret, errmsg.SuccessMsg())
	return
}
